#include "window.h"

Window::Window(QWidget *parent) :
    QWidget(parent)
{

    qsrand(time(0));
    m_prevTimeSec = m_prevScore = m_prevTimeMin = m_prevTimeMSec = 0;
    m_killed = true;
    font = new QFont("Arial",18,5);
    m_playedTimer = new QElapsedTimer();
    m_pixmap = QPixmap("background.png");
    m_canCreateMeteorit = false;
    m_activePause = true;
    m_canStartMeteoritTimer = false;
    m_frequencyMeteorits = 1000;
    m_lifeTime = m_destroyedMeteorites = 0;
    m_up = m_down = m_right = m_left = m_fire = m_canCreateBullet = false;
    setWindowTitle(tr("Starship"));
    setFixedHeight(500);
    setFixedWidth(500);
    m_hp = 3;
    setMouseTracking(true);
    m_ship = new Starship(250, 250);
    connect(this,SIGNAL(updateShip(qint32,qint32)), m_ship, SLOT(updateLocation(qint32,qint32)));
    connect(this,SIGNAL(transmitCursor(qint32,qint32)), m_ship, SLOT(receiptCursor(qint32,qint32)));
    connect(m_ship,SIGNAL(transmitShipInfo(qint32,qint32,double)),this,SLOT(updateShipInfo(qint32,qint32,double)));
    QTimer *timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(updateWindow()));
    timer->start(10);
    pause();


}
void Window::paintEvent (QPaintEvent *e) //я твой огнетушитель пыш пыш
{
    setFont(*font);
    QPainter *painter = new QPainter(this);
    painter->drawPixmap(- m_pixmap.width() / 2.0, -m_pixmap.height() / 2.0, m_pixmap);
    if (m_killed == false)
    {
        painter->drawText(50, 20, "score : " + QString::number(m_score));
        painter->drawText(180, 20, "time : " + QString::number(m_playedTimer->elapsed()/1000/60)
                          + ":" + QString::number(m_playedTimer->elapsed()/1000%60) + ":"
                          + QString::number((m_playedTimer->elapsed()%1000)/100));
        painter->drawText(370, 20, "HP : " + QString::number(m_hp));
    }
    else
    {
        painter->drawText(50, 20, "score : " + QString::number(m_prevScore));
        painter->drawText(180, 20, "time : " + QString::number(m_prevTimeMin)
                          + ":" + QString::number(m_prevTimeSec) + ":"
                          + QString::number(m_prevTimeMSec));
        painter->drawText(370, 20, "HP : " + QString::number(0));
        painter->drawText(130,150,"Press ENTER to start");
    }

    m_ship->draw(painter);

    for (int i = 0; i < m_listBullet.size(); ++i)
        if (!m_listBullet[i]->update())
            m_listBullet.erase(m_listBullet.begin()+i);
    for (int i = 0; i < m_listMeteorites.size(); ++i)
        if (!m_listMeteorites[i]->update())
            m_listMeteorites.erase(m_listMeteorites.begin()+i);


    for (int i = 0; i < m_listBullet.size(); ++i)
        m_listBullet[i]->draw(painter);

    for (int i = 0; i < m_listMeteorites.size(); ++i)
        m_listMeteorites[i]->draw(painter);

    if (m_killed == true)
        m_listMeteorites.clear();

    collisionMB();
    collisionMS();

    timerMeteorits();

    if (m_fire)
    {
        if (m_canCreateBullet == false)
        {
             m_canCreateBullet = true;
             m_listBullet.push_back(new Bullet((double)m_xShip,(double)m_yShip,m_angleShip));
             QTimer *timer = new QTimer(this);
             timer->singleShot(200,this,SLOT(CreateBullet()));

        }

    }
    painter->end();

}
void Window::mouseMoveEvent(QMouseEvent *e)
{
    m_x = e->x();
    m_y = e->y();
   // repaint();
   // m_angle = atan2(toY - m_y, toX - m_x);
}
void Window::mousePressEvent(QMouseEvent *e)
{
    if (e->button()==Qt::LeftButton)
        m_fire = true;
}
void Window::mouseReleaseEvent(QMouseEvent *e)
{
    if (e->button()==Qt::LeftButton)
        m_fire = false;
}
void Window::keyPressEvent(QKeyEvent *e)
{
    if (e->key() == Qt::Key_W)
        m_up = true;
    if (e->key() == Qt::Key_S)
        m_down = true;
    if (e->key() == Qt::Key_A)
        m_left = true;
    if (e->key() == Qt::Key_D)
        m_right = true;
    if (e->key() == Qt::Key_Return)
    {
        m_killed = false;
        m_activePause = true;
        start();
    }
    if (!m_activePause && e->key() == Qt::Key_Space)
        pause();
}
void Window::keyReleaseEvent(QKeyEvent *e)
{
    if (e->key() == Qt::Key_W)
        m_up = false;
    if (e->key() == Qt::Key_S)
        m_down = false;
    if (e->key() == Qt::Key_A)
        m_left = false;
    if (e->key() == Qt::Key_D)
        m_right = false;

}
void Window::start()
{
   // QMessageBox::warning(this, tr("Start"), tr("Work"));

    if (m_killed == false)
        m_playedTimer->start();
    m_listBullet.clear();
    m_listMeteorites.clear();
    m_score = 0;
    m_hp = 3;
    m_lifeTime = m_destroyedMeteorites = 0;
    m_up = m_down = m_right = m_left = m_fire = false;
   // repaint();
}
void Window::pause()
{
    //все замораживаем выводим стату
    m_activePause = false;
    start();
}
void Window::updateWindow()
{
    qint32 tempX=0,tempY=0;
    if (m_up)
        tempY-=2;
    if (m_down)
        tempY+=2;
    if (m_left)
        tempX-=2;
    if (m_right)
        tempX+=2;
    emit updateShip(tempX,tempY);
    emit transmitCursor(m_x,m_y);
    repaint();
}
void Window::updateShipInfo(qint32 x, qint32 y, double angle)
{
    m_xShip = x;
    m_yShip = y;
    m_angleShip = angle;
}

void Window::CreateBullet()
{
    m_canCreateBullet = false;
}

void Window::addMeteorit()
{
    double meteoriteBeginX,meteoriteBeginY,meteoriteEndX,meteoriteEndY,angle;
    double angleInDegrees;
    qint32 axis; //0 = верх, 1 = низ, 2 = лево, 3 = право
    axis = rand() % 4;
    switch (axis) {
    case 0:
        meteoriteBeginX = rand() % 500;
        meteoriteBeginY = 530;
        meteoriteEndX = rand() % 500;
        meteoriteEndY = -30;
        break;
    case 1:
        meteoriteBeginX = rand() % 500;
        meteoriteBeginY = -30;
        meteoriteEndX = rand() % 500;
        meteoriteEndY = 530;
        break;
    case 2:
        meteoriteBeginX = -30;
        meteoriteBeginY = rand() % 500;
        meteoriteEndX = 530;
        meteoriteEndY = rand() % 500;
        break;
    case 3:
        meteoriteBeginX = 530;
        meteoriteBeginY = rand() % 500;
        meteoriteEndX = -30;
        meteoriteEndY = rand() % 500;
        break;
    default:
        break;
    }
    angle = atan2(meteoriteEndY - meteoriteBeginY, meteoriteEndX - meteoriteBeginX);
    angleInDegrees = angle <= 0.0
    ? angle * 180.0 / 3.14159265359
    : angle * 180.0 / 3.14159265359 - 360.0;
    m_listMeteorites.push_back(new Meteorites(meteoriteBeginX,meteoriteBeginY,angle,angleInDegrees));
}
void Window::CreateMeteorit()
{
    m_canCreateMeteorit = false;
}

void Window::timerMeteorits()
{
    if (m_canStartMeteoritTimer == false)
    {
        m_canStartMeteoritTimer = true;
        QTimer *mainTimer = new QTimer(this);
        mainTimer->singleShot(5000,this,SLOT(increaseFrequencyMeteorits()));
    }
    if (m_canCreateMeteorit == false)
    {
        m_canCreateMeteorit = true;
        addMeteorit();
        QTimer *timer = new QTimer(this);
        timer->singleShot(m_frequencyMeteorits,this,SLOT(CreateMeteorit()));
    }
}
void Window::increaseFrequencyMeteorits()
{
    m_frequencyMeteorits -= 50;
    m_frequencyMeteorits = std::max(m_frequencyMeteorits,50);
    m_canStartMeteoritTimer = false;
}
void Window::collisionMB()
{
    QMutableListIterator<Bullet*> i(m_listBullet);
    while (i.hasNext())
    {
        double xB,yB;
        Bullet *b = i.next();
        QMutableListIterator<Meteorites*> j(m_listMeteorites);
        QPointF locateBullet = b->locate();
        xB = locateBullet.x();
        yB = locateBullet.y();
        while (j.hasNext())
        {
            double xM,yM;
            Meteorites *m = j.next();
            QPointF localeMeteorite = m->locate();
            xM = localeMeteorite.x();
            yM = localeMeteorite.y();
            if (sqrt((xB-xM)*(xB-xM)+(yB-yM)*(yB-yM)) <= 20.0+5.0)
            {
                m_score++;
                delete b;
                delete m;
                j.remove();
                i.remove();
                break;
            }
        }
    }
}
void Window::collisionMS()
{
    bool check = false;
    QMutableListIterator<Meteorites*> i(m_listMeteorites);
    while (i.hasNext())
    {
        double xM,yM;
        Meteorites *m = i.next();
        QPointF locateBullet = m->locate();
        xM = locateBullet.x();
        yM = locateBullet.y();
        if (sqrt((m_xShip-xM)*(m_xShip-xM)+(m_yShip-yM)*(m_yShip-yM)) <= 25.0+16.0)
        {
            m_hp--;
            if (m_hp == 0)
            {
                check = true;
                break;
            }
            delete m;
            i.remove();
        }
    }
    if (check == true)
    {
        m_prevScore = m_score;
        m_prevTimeMin = m_playedTimer->elapsed()/1000/60;
        m_prevTimeSec = m_playedTimer->elapsed()/1000%60;
        m_prevTimeMSec = (m_playedTimer->elapsed()%1000)/100;
        m_killed = true;
        pause();
    }
}
